﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MuseLibrary.EncodingHelpers
{
    public class RemainderParser
    {
        public RemainderParser()
        {

        }

        public RemainderParser(int alphabetSize)
        {
            ResetState(alphabetSize);
        }

        private int _alphabetSize;
        private int _minBits;
        private int _minValueForMaxBits;
        private List<bool> _bitArray = new List<bool>();
        private int _remainder;

        public int Remainder
        {
            get { return _remainder; }
        }

        public void ResetState(int alphabetSize)
        {
            _alphabetSize = alphabetSize;
            _bitArray.Clear();
            _minBits = 0;
            while (alphabetSize > 1)
            {
                _minBits++;
                alphabetSize >>= 1;
            }

            _minValueForMaxBits = (1 << (_minBits + 1)) - _alphabetSize;
        }

        public bool ReadBit(bool bit)
        {
            _bitArray.Add(bit);
            if (_bitArray.Count < _minBits)
                return false;

            _remainder = _bitArray.ToInteger();
            if (_bitArray.Count == _minBits + 1)
            {
                _remainder -= _minValueForMaxBits;
                return true;
            }

            return _remainder < _minValueForMaxBits;
        }


        public static int ToBinary(int value, int codewordLength, out int bits)
        {
            var output = 0;
            bits = 0;
            while (value != 0)
            {
                if ((value % 2) != 0)
                {
                    output += 1 << bits;
                }

                bits++;
                value >>= 1;
            }

            while (bits < codewordLength)
            {
                bits++;
            }

            return output;
        }
    }
}
